<!-- 
  菜单选择组件
  1、获取所有的菜单数据
  2、过滤菜单数据
 -->

<template>
  <el-space class="menu-check" direction="vertical">
    <div class="menu-check_header">
      <el-input placeholder="输入关键字进行过滤" v-model="filterText" />
    </div>
    <div class="menu-check_body">
      <el-scrollbar height="200">
        <el-tree
          ref="treeRef"
          node-key="id"
          :data="treeData"
          :props="{ label: 'name' }"
          :filter-node-method="filterNode"
          show-checkbox
          @check="handleCheck"
        ></el-tree>
      </el-scrollbar>
    </div>
  </el-space>
</template>
<script>
import { getSysMenuList } from "@/api/sys.js";
import { listToTree } from "@/utils/common";
export default {
  name: "MenuCheck",
  props: ["modelValue"],
  emits: ["update:modelValue"],
  data() {
    return {
      filterText: "",
      menus: [],
    };
  },
  watch: {
    modelValue: {
      handler(newVal) {
        const keys = newVal.filter((item) => {
          // 判断item 这个ID是否为叶子节点ID
          return this.menus.every((menu) => menu.parentId !== item);
        });
        this.$nextTick(() => {
          this.$refs.treeRef?.setCheckedKeys(keys);
        });
      },
      deep: true,
      immediate: true,
    },
    filterText(newVal) {
      this.$refs.treeRef.filter(newVal);
    },
  },
  computed: {
    // 菜单数据
    treeData() {
      return listToTree(this.menus);
    },
  },

  methods: {
    async refresh() {
      const result = await getSysMenuList();
      this.menus = result;
      // console.log(result);
    },
    // 获取勾选和半勾选的id集合
    handleCheck() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      // 触发 update:modelValue 自定义事件
      this.$emit("update:modelValue", keys);
      // console.log(keys);
    },
    filterNode(value, node) {
      // console.log("value", value);
      // console.log("node", node);
      return node.name.includes(value);
    },
  },
  created() {
    this.refresh();
  },
};
</script>
<style scoped>
.menu-check_body {
  margin-top: 10px;
  padding: 5px 0;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  /* height: 200px;
  overflow-y: auto; */
}
.menu-check {
  width: 100%;
}
.el-space {
  display: block;
}
</style>
